from flask import request, jsonify
from services.car_service import CarService
import logging

logger = logging.getLogger(__name__)

class CarController:
    """汽车品牌和车型控制器"""
    
    def __init__(self):
        self.car_service = CarService()
    
    def get_all_brands(self):
        """获取所有汽车品牌"""
        try:
            brands = self.car_service.get_all_brands()
            return jsonify({
                'success': True,
                'data': brands,
                'message': '获取品牌列表成功'
            })
        except Exception as e:
            logger.error(f"获取品牌列表失败: {str(e)}")
            return jsonify({
                'success': False,
                'data': [],
                'message': '获取品牌列表失败'
            }), 500
    
    def get_popular_brands(self):
        """获取热门品牌"""
        try:
            limit = request.args.get('limit', 8, type=int)
            brands = self.car_service.get_popular_brands(limit)
            return jsonify({
                'success': True,
                'data': brands,
                'message': '获取热门品牌成功'
            })
        except Exception as e:
            logger.error(f"获取热门品牌失败: {str(e)}")
            return jsonify({
                'success': False,
                'data': [],
                'message': '获取热门品牌失败'
            }), 500
    
    def get_cars_by_brand(self, brand_id):
        """根据品牌ID获取车型列表"""
        try:
            page = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 10, type=int)
            
            result = self.car_service.get_cars_by_brand(brand_id, page, per_page)
            return jsonify({
                'success': True,
                'data': result,
                'message': '获取车型列表成功'
            })
        except Exception as e:
            logger.error(f"获取车型列表失败: {str(e)}")
            return jsonify({
                'success': False,
                'data': {'cars': [], 'total': 0, 'page': 1, 'per_page': 10, 'pages': 0},
                'message': '获取车型列表失败'
            }), 500
    
    def get_popular_cars_by_brand(self, brand_id):
        """获取品牌下的热门车型"""
        try:
            limit = request.args.get('limit', 5, type=int)
            cars = self.car_service.get_popular_cars_by_brand(brand_id, limit)
            return jsonify({
                'success': True,
                'data': cars,
                'message': '获取热门车型成功'
            })
        except Exception as e:
            logger.error(f"获取热门车型失败: {str(e)}")
            return jsonify({
                'success': False,
                'data': [],
                'message': '获取热门车型失败'
            }), 500
    
    def search_cars(self):
        """搜索车型"""
        try:
            keyword = request.args.get('keyword', '')
            page = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 10, type=int)
            
            result = self.car_service.search_cars(keyword, page, per_page)
            return jsonify({
                'success': True,
                'data': result,
                'message': '搜索成功'
            })
        except Exception as e:
            logger.error(f"搜索车型失败: {str(e)}")
            return jsonify({
                'success': False,
                'data': {'cars': [], 'total': 0, 'page': 1, 'per_page': 10, 'pages': 0},
                'message': '搜索失败'
            }), 500
    
    def get_car_detail(self, car_id):
        """获取车型详情"""
        try:
            car = self.car_service.get_car_detail(car_id)
            if car:
                return jsonify({
                    'success': True,
                    'data': car,
                    'message': '获取车型详情成功'
                })
            else:
                return jsonify({
                    'success': False,
                    'data': None,
                    'message': '车型不存在'
                }), 404
        except Exception as e:
            logger.error(f"获取车型详情失败: {str(e)}")
            return jsonify({
                'success': False,
                'data': None,
                'message': '获取车型详情失败'
            }), 500
    
    def get_cars(self):
        """获取所有车型（支持分页和筛选）"""
        try:
            # 获取查询参数
            page = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 10, type=int)
            brand_id = request.args.get('brand_id', type=int)
            price_range = request.args.get('price_range')
            min_price = request.args.get('min_price', type=float)
            max_price = request.args.get('max_price', type=float)
            energy_type = request.args.get('energy_type')
            level = request.args.get('level')
            start_date = request.args.get('start_date')
            end_date = request.args.get('end_date')
            keyword = request.args.get('keyword')
            sort_by = request.args.get('sort_by')  # 新增排序字段参数
            order = request.args.get('order')      # 新增排序方向参数
            
            result = self.car_service.get_cars_with_filters(
                page=page,
                per_page=per_page,
                brand_id=brand_id,
                price_range=price_range,
                min_price=min_price,
                max_price=max_price,
                energy_type=energy_type,
                level=level,
                start_date=start_date,
                end_date=end_date,
                keyword=keyword,
                sort_by=sort_by,  # 传递排序参数
                order=order       # 传递排序参数
            )
            
            return jsonify({
                'success': True,
                'data': result,
                'message': '获取车型列表成功'
            })
        except Exception as e:
            logger.error(f"获取车型列表失败: {str(e)}")
            return jsonify({
                'success': False,
                'data': {'cars': [], 'total': 0, 'page': 1, 'per_page': 10, 'pages': 0},
                'message': '获取车型列表失败'
            }), 500